class SceneMain extends Scene {
  blocks = []
  numberOfBlock = 30

  paddle = new Paddle()
  ball = new Ball()
  score = new Score()

  constructor(...args) {
    super(...args)
    this.setup()
  }

  update() {
    const { ball, paddle, game } = this
    if (game.over) {
      return
    }
    ball.update()
    if (utils.intersect(paddle, ball)) {
      ball.bounce()
    }
    this.updateBlocks()

    if (ball.y + ball.h > 400) {

      console.log('游戏结束');
      var scene_over = new SceneOver(game, this.score.score)
      game.runWithScene(scene_over)
      game.over = true;
    }
  }

  updateBlocks() {
    const { blocks, ball, score } = this

    if (blocks.length == 0) {
      // 过关
    }
    blocks.forEach(b => {
      if (utils.intersect(ball, b)) {
        /* 相撞 */
        console.log('小球与砖块相撞');
        ball.bounce()
        let index = blocks.indexOf(b)
        if (index > -1) {
          score.plus()
          blocks.splice(index, 1)
          this.remove(b)
        }
      }
    })
  }
  setup() {
    const { game, paddle, ball, score } = this

    this.add(paddle)
    this.add(ball)
    this.add(score)
    this.addBlocks()

    window.addEventListener('keyup', (event) => {
      if (event.key == 'f') {
        this.ball.fire()
      }
    })

    game.registerAction('a', function () {
      paddle.moveLeft()
    })
    game.registerAction('d', function () {
      paddle.moveRight()
    })
  }

  addBlocks() {
    for (let i = 0; i < this.numberOfBlock; i++) {

      let x = i * 60
      let y = 50
      let color = 'blue'

      if (i >= 10 && i < 20) {
        x = (i - 10) * 60
        y = 80
        color = 'green'
      } else if (i >= 20) {
        x = (i - 20) * 60
        y = 110
        color = 'red'
      }

      const b = new Block(x, y, color)

      this.add(b)
      this.blocks.push(b)
    }
  }
}